<template>
  <el-dialog v-model="ifShow" title="新增明细" @close="close()">
    <el-form :model="form" label-width="100" ref="formRef" :rules="rules">
      <el-form-item label="是否开票" prop="invoice">
        <el-switch v-model="form.invoice" active-text="是" inactive-text="否" active-value="是" inactive-value="否"/>
      </el-form-item>
      <el-form-item label="收款金额" prop="payment_amount">
        <el-input-number v-model="form.payment_amount" :min="0"/>
      </el-form-item>
      <el-form-item label="开票时间" prop="time">
        <el-date-picker v-model="form.time" value-format="YYYY/MM/DD" format="YYYY/MM/DD"/>
      </el-form-item>
      <el-form-item label="开票文件" prop="invoice_path">
        <file-uploader v-model="form.invoice_path" v-model:company-id="companyId"/>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input type="textarea" v-model="form.remarks"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import {inject, type Ref, ref, useTemplateRef, watchEffect} from "vue";
import type {ProjectDetailVO} from "../../../types/project";
import FileUploader from "../../../components/FileUploader.vue";
import {ElMessage, type FormInstance, type FormRules} from "element-plus";
import {useMutation} from "@pinia/colada";
import {addProjectDetail} from "../../../api/project_detail.ts";


const emits = defineEmits<{
  success: []
}>();

const ifShow = defineModel({
  default: false
})

const projectId = defineModel<number>("projectId")

const companyId = inject<Ref<number>>("companyId");

const form = ref<ProjectDetailVO>({
  payment_amount: 0,
})

watchEffect(() => {
  form.value.company_project_id = projectId.value
})

const rules = ref<FormRules<ProjectDetailVO>>({
  payment_amount: [
    {required: true, message: '请填入收款金额！'},
  ],
  time: [
    {required: true, message: '请选择开票时间！'}
  ],
  invoice_path: [
    {required: true, message: '请上传发票文件！'}
  ]
})

const formRef = useTemplateRef<FormInstance>('formRef');

let {mutate: addProjectDetailFn} = useMutation({
  mutation: (projectDetail: ProjectDetailVO) => addProjectDetail(projectDetail),
  onSuccess: () => {
    ElMessage.success("添加成功！");
    ifShow.value = false
    emits('success')
  }
});

const submitForm = async () => {
  await formRef.value?.validate((valid) => {
    if (valid) {
      addProjectDetailFn(form.value)
    }
  })
}
const close = () => {
  formRef.value?.resetFields();
}
</script>

<style scoped>

</style>